package cn.service.impl;

import cn.service.AttributeListService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import entity.*;
import mapper.AttributeMapper;
import mapper.AttributeValueMapper;
import mapper.CategoryAttributesMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service
public class AttributeListServiceImpl implements AttributeListService {
    @Resource
    CategoryAttributesMapper categoryAttributesMapper;

    @Resource
    AttributeMapper attributeMapper;

    @Resource
    AttributeValueMapper attributeValueMapper;

    @Override
    public Result queryAttributeList(Long parent_id,Integer currentPage,Integer pageSize) {
        List<Integer> attribute_idlist = categoryAttributesMapper.queryByCategory_id(parent_id);//获得attribute_id集合
        PageHelper.startPage(currentPage,pageSize);
        List<Attribute> attributelist = attributeMapper.queryByAttribute_ids(attribute_idlist);//根据attribute_id集合查询attribute对象集合
        Page<Attribute> page = (Page<Attribute>)attributelist;
        return Result.success((int)page.getTotal(),attributelist);
    }

    @Override
    public Result addAttributeList(DTO dto) {
        //测试DTO{attribute_name='asas', isChooseList='casca', name='服装-外套', parent_id=1}
        //判断属性名称是否重复
        if (attributeMapper.queryByAttribute_name(dto.getAttribute_name()) == null) {//attribute_name在attribute表中不存在,可以添加
            Attribute attribute = new Attribute(dto.getAttribute_name());
            attributeMapper.insertSelective(attribute);
            Integer attribute_id = attribute.getAttribute_id();
            CategoryAttributes categoryAttributes = new CategoryAttributes(dto.getParent_id(), attribute_id);
            categoryAttributesMapper.insertSelective(categoryAttributes);
            List<String> attributeValueList = getAttributeValueList(dto.getIsChooseList());
            for (String s : attributeValueList) {
                AttributeValue attributeValue = new AttributeValue(attribute_id,s);
                attributeValueMapper.insertSelective(attributeValue);
            }
            return Result.success(200,"添加成功!");
        } else {
            return Result.fail(500,"添加失败,属性名称已存在!");
        }
    }

    /**
     * 将输入的isChooseList字符串转为attribute value集合
     * @param isChooseList
     * @return
     */
    public List<String> getAttributeValueList(String isChooseList) {
        String[] array = isChooseList.split(",");
        return Arrays.asList(array);
    }


}
